package com.xpengplayer.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.xpengplayer.R;
import com.xpengplayer.data.FavoriteDirectory;
import com.xpengplayer.data.FavoriteDirectoryManager;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 目录浏览器Activity
 * 用于浏览文件系统、选择视频文件和收藏目录
 */
public class DirectoryBrowserActivity extends AppCompatActivity {
    
    public static final String EXTRA_DIRECTORY_PATH = "com.xpengplayer.extra.DIRECTORY_PATH";
    public static final String EXTRA_SELECTED_VIDEO_PATH = "com.xpengplayer.extra.SELECTED_VIDEO_PATH";
    private static final int PERMISSION_REQUEST_STORAGE = 1001;
    
    private TextView currentPathText;
    private ListView fileList;
    private Button backButton;
    private Button favoriteButton;
    
    private String currentPath;
    private List<FileItem> fileItems = new ArrayList<>();
    private FavoriteDirectoryManager favoriteManager;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_directory_browser);
        
        // 初始化UI组件
        currentPathText = findViewById(R.id.current_path_text);
        fileList = findViewById(R.id.file_list);
        backButton = findViewById(R.id.back_button);
        favoriteButton = findViewById(R.id.favorite_button);
        
        // 初始化收藏管理器
        favoriteManager = new FavoriteDirectoryManager(this);
        
        // 获取传入的目录路径
        String path = getIntent().getStringExtra(EXTRA_DIRECTORY_PATH);
        currentPath = path != null ? path : Environment.getExternalStorageDirectory().getAbsolutePath();
        
        // 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) 
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, 
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_STORAGE);
        } else {
            loadDirectory(currentPath);
        }
        
        // 设置返回按钮点击事件
        backButton.setOnClickListener(v -> {
            File file = new File(currentPath);
            File parent = file.getParentFile();
            if (parent != null && parent.canRead()) {
                currentPath = parent.getAbsolutePath();
                loadDirectory(currentPath);
            }
        });
        
        // 设置收藏按钮点击事件
        favoriteButton.setOnClickListener(v -> {
            toggleFavoriteDirectory();
        });
        
        // 设置列表点击事件
        fileList.setOnItemClickListener((parent, view, position, id) -> {
            FileItem item = fileItems.get(position);
            if (item.isDirectory) {
                // 进入子目录
                currentPath = item.file.getAbsolutePath();
                loadDirectory(currentPath);
            } else {
                // 选择视频文件
                Intent resultIntent = new Intent();
                resultIntent.putExtra(EXTRA_SELECTED_VIDEO_PATH, item.file.getAbsolutePath());
                setResult(RESULT_OK, resultIntent);
                finish();
            }
        });
    }
    
    /**
     * 加载目录内容
     */
    private void loadDirectory(String path) {
        currentPathText.setText(path);
        
        // 更新收藏按钮状态
        updateFavoriteButton();
        
        File directory = new File(path);
        if (!directory.exists() || !directory.isDirectory() || !directory.canRead()) {
            Toast.makeText(this, "无法访问目录", Toast.LENGTH_SHORT).show();
            return;
        }
        
        fileItems.clear();
        
        // 获取目录中的所有文件
        File[] files = directory.listFiles();
        if (files != null) {
            List<File> dirList = new ArrayList<>();
            List<File> videoList = new ArrayList<>();
            
            // 分离目录和视频文件
            for (File file : files) {
                if (file.isDirectory() && file.canRead() && !file.isHidden()) {
                    dirList.add(file);
                } else if (isVideoFile(file)) {
                    videoList.add(file);
                }
            }
            
            // 对目录和视频文件进行排序
            Collections.sort(dirList, Comparator.comparing(File::getName, String.CASE_INSENSITIVE_ORDER));
            Collections.sort(videoList, Comparator.comparing(File::getName, String.CASE_INSENSITIVE_ORDER));
            
            // 添加到显示列表
            for (File dir : dirList) {
                fileItems.add(new FileItem(dir, true));
            }
            for (File video : videoList) {
                fileItems.add(new FileItem(video, false));
            }
        }
        
        // 创建显示列表
        List<String> displayList = new ArrayList<>();
        for (FileItem item : fileItems) {
            if (item.isDirectory) {
                displayList.add("[目录] " + item.file.getName());
            } else {
                displayList.add(item.file.getName());
            }
        }
        
        // 设置适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_list_item_1,
                displayList
        );
        fileList.setAdapter(adapter);
    }
    
    /**
     * 切换目录收藏状态
     */
    private void toggleFavoriteDirectory() {
        if (favoriteManager.isDirectoryFavorited(currentPath)) {
            // 取消收藏
            if (favoriteManager.removeFavorite(currentPath)) {
                Toast.makeText(this, "已取消收藏", Toast.LENGTH_SHORT).show();
            }
        } else {
            // 添加收藏
            File dir = new File(currentPath);
            FavoriteDirectory favoriteDir = new FavoriteDirectory(currentPath, dir.getName());
            if (favoriteManager.addFavorite(favoriteDir)) {
                Toast.makeText(this, "已添加收藏", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "添加收藏失败", Toast.LENGTH_SHORT).show();
            }
        }
        updateFavoriteButton();
    }
    
    /**
     * 更新收藏按钮状态
     */
    private void updateFavoriteButton() {
        if (favoriteManager.isDirectoryFavorited(currentPath)) {
            favoriteButton.setText("取消收藏");
        } else {
            favoriteButton.setText("添加收藏");
        }
    }
    
    /**
     * 检查文件是否为视频文件
     */
    private boolean isVideoFile(File file) {
        if (!file.isFile() || !file.canRead() || file.isHidden()) {
            return false;
        }
        
        String name = file.getName().toLowerCase();
        return name.endsWith(".mp4") || name.endsWith(".mkv") || 
               name.endsWith(".avi") || name.endsWith(".mov") ||
               name.endsWith(".wmv") || name.endsWith(".flv");
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                loadDirectory(currentPath);
            } else {
                Toast.makeText(this, "需要存储权限才能浏览文件", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
    
    /**
     * 文件项内部类
     */
    private static class FileItem {
        File file;
        boolean isDirectory;
        
        FileItem(File file, boolean isDirectory) {
            this.file = file;
            this.isDirectory = isDirectory;
        }
    }
}